package com.example.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.common.utils.AesUtil;
import com.example.common.utils.JwtUtil;
import com.example.sys.entity.User;
import com.example.sys.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(request.getRequestURL().indexOf("login") != -1 || request.getRequestURL().indexOf("files") != -1) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");
        try {
            token = AesUtil.decrypt(token);
        } catch (Exception e) {
            log.error("解密失败：{}", e);
        }
        response.setContentType("text/html;charset=utf-8");
        if(StringUtils.isBlank(token)) {
            log.warn("用户未登陆");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().println("请先登陆");
            return;
        }
        if(JwtUtil.isExpire(token)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().println("会话过期，请重新登陆");
            return;
        }
        String userInfo = redisTemplate.opsForValue().get(token);
        log.info("当前会话Token：{}", token);
        log.info("缓存信息：{}", userInfo);
        User user = JSONObject.parseObject(userInfo, User.class);
        user.setToken(token);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null,
                        AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoleName()));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
